﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cos.Core.NHibernate;
using Cos.Core.NHibernate.Util;
using Cos.Module.CMS.Data;
using NHibernate;
using NHibernate.Criterion;

namespace Cos.Module.CMS.NHibernate
{
    using System;

    using Cos.Core.NHibernate;
    using Cos.Core.NHibernate.Util;
    using Cos.Module.CMS.Data;

    using global::NHibernate;

    public class NavRepository : RepositoryBase, INavRepository
    {
        public NavRepository(ISessionFactory sessionFactory) 
            : base(sessionFactory)
        {
        }

        public Core.Model.Content.Nav GetNav(int navId)
        {
            var navDataModel = this.CurrentSession.Get<NavDataModel>(navId);

            if (navDataModel == null)
            {
                return null;
            }

            return CMSModelConverter.ToNav(navDataModel);
            
        }

        public Core.Model.Content.Nav SaveNav(Core.Model.Content.Nav nav)
        {
            var navDataModel = this.CurrentSession.Get<NavDataModel>(nav.NavId).ToNavDataModel(nav);

            this.CurrentSession.SaveOrUpdate(navDataModel);

            this.CurrentSession.Flush();

            return navDataModel.ToNav();
        }

        public void DeleteNav(Core.Model.Content.Nav nav)
        {
            this.CurrentSession.Delete(this.CurrentSession.Get<NavDataModel>(nav.NavId).ToNavDataModel(nav));
        }

        public int NextNavOrder(int parentNavId)
        {
            var navDataModel = this.CurrentSession.Get<NavDataModel>(parentNavId);

            if (navDataModel == null)
            {
                return 1;
            }

            var subPages = this.CurrentSession.CreateCriteria<NavDataModel>().Add(Restrictions.Eq("ParentId", parentNavId)).List<NavDataModel>();

            return subPages.Count + 1;
        }
    }
}
